$j(document).ready(function () {
	//验证
	
});

$j.fn.extend({
	loading2:function(){
		return this.each(function(){
			$j(this).html('<td colspan="12"><div class="loading_box"><div class="progress_bar"><img src="'+__ctxPath+'/images/icon/loadingBig.gif"/>loading...</div></div></td>');			
		});
	},
	loading3:function(){
		return this.each(function(){
			$j(this).html('<td colspan="12"><div class="loading_box"><div class="progress_bar"><img src="'+__ctxPath+'/images/icon/loadingBig.gif"/>'+__FMT.salesOrder_processing+'</div></div></td>');			
		});
	},
	loading4:function(){
		return this.each(function(){
			$j(this).html('<div class="loading_box"><div class="progress_bar"><img src="'+__ctxPath+'/images/icon/loadingBig.gif"/>'+__FMT.salesOrder_editPanel_handling+'</div></div>');			
		});
	}
});

//自动以的setTimeout方法，可传递参数
function masterSetTimeout(callback,timeout,param)
{
    var args = Array.prototype.slice.call(arguments,2);
    var _cb = function()
    {
        callback.apply(null,args);
    }  
    window.setTimeout(_cb,timeout);
}



//显示操作按钮
function displayListButtons(status){
	
}
//显示 隐藏全部
function toggleScreenAll(linkDOM){
	if($j(linkDOM).hasClass("expand")){
		$j(linkDOM).removeClass("expand").addClass("shrink");
		$j('span.toggleScreen').each(function(){
			var jTrThis = $j(this).parents('tr:first');
			var jTrFull = jTrThis.next();
			var orderId = jTrThis.attr("orderId");
			jTrFull.show();
			if(!jTrFull.hasClass("hasLoad")){
				jTrFull.addClass("hasLoad");
				jTrFull.loading2().load(__ctxPath+'/order/salesOrder/blank.html?doAction=showOrderItem&salesOrderId='+orderId);
			}
			$j(this).removeClass("expand").addClass("shrink");
		});
	
	}else{
		$j(linkDOM).removeClass("shrink").addClass("expand");
		$j('span.toggleScreen').each(function(){
			var jTrThis = $j(this).parents('tr:first');
			var jTrFull = jTrThis.next();
			jTrFull.hide();
			$j(this).removeClass("shrink").addClass("expand");
		});
	}
}	

//显示 隐藏详细
function toggleScreen(linkDOM){
	var jTrThis = $j(linkDOM).parents('tr:first');
	var jTrFull = jTrThis.next();
	var orderId = jTrThis.attr("orderId");
	if(jTrFull.is(":hidden")){
		jTrFull.show();
		$j(linkDOM).removeClass("expand").addClass("shrink");
		
		if(!jTrFull.hasClass("hasLoad")){
			jTrFull.addClass("hasLoad");
			jTrFull.loading2().load(__ctxPath+'/order/salesOrder/blank.html?doAction=showOrderItem&salesOrderId='+orderId);
		}
	}else{
		jTrFull.hide();
		$j(linkDOM).removeClass("shrink").addClass("expand");
	}
	
}


//编辑订单
function editOrder(orderId){
	var url = __ctxPath+"/order/salesOrder/ajaxPage.html?doAction=edit&direct=false&salesOrderId="+orderId;
	showOrderForm(url,null);
}

//在本页以ajaxPage方式打开Form 
function showOrderForm(url,param){
	$j('#mainDiv').hide();
	$j('#formDiv').show().loading().load(url,param);
}


//刷新订单列表
function refreshOrderList(){
	searchOrders(false);
}
//分页
function fnOnGoToPage(){
	refreshOrderList();
}

//对已有结果进行排序,ascValue表示升序时对应的值,descValue表示降序时对应的值
function sortField(linkDOM,ascValue,descValue){
	var jThDOM = $j(linkDOM).parent('th');
	if(jThDOM.hasClass("order1")){
		$j('#storageOrderby').val(descValue);
	}else{
		$j('#storageOrderby').val(ascValue);
	}
	searchOrders(false);
}

//搜索订单 isNew标示是否新的搜索,param标示是否自定义参数搜索
function searchOrders(isNew,param){
	var postData;
	var url;
	if(isNew){
		if(null==param){
			if(validateSearchCriteria()){
				//有搜索结果搜索
			    postData = $j('#orderSearchCriteria :input').serializeArray();
			    url=__ctxPath+"/order/salesOrder/blank.html?doAction=search&btnSearch=1&isSearchResult=1";
				$j("#orderResults").loading().load(url,postData);
		    }else{
		    	return;
		    }
		}else{
			//新的搜索。全部，上架等
			//有搜索结果搜索
			if(param.quickFilter != undefined){
				$j('#orderResults #quickFilter').val(param.quickFilter);
			}
		    postData = $j('#orderResults :input').serializeArray();
		    url=__ctxPath+"/order/salesOrder/blank.html?doAction=search&btnSearch=1";
			$j("#orderResults").loading().load(url,postData);  
		}    
	}else{
		postData = $j('#orderResults :input').serializeArray();
		url=__ctxPath+"/order/salesOrder/blank.html?&doAction=search";
		$j("#orderResults").loading().load(url,postData);  
	} 
	
}



//验证函数
function validateSearchCriteria(){
	if(!validateForm($j('#orderSearchCriteria').get(0))){
    	return false;
   	}
   	return true;
}

//重设搜索条件
function resetSearchCriteria(){
	fnResetForm("orderSearchCriteria");
	$j('#orderSearchCriteria input[name="regionId"]').val("");//重置注册地区
	$j('#orderSearchCriteria select[name="regionName"]').each(function(){
		if($j(this).prevAll('select[name="regionName"]').length>=1){
			$j(this).remove();
		}
		
	});
	
}

						
//显示操作按钮 isCanReturnMoney表示是否能退款
function displayButtons(salesOrderId,orderStatus,paymentStatus,shipmentStatus,isCanReturnMoney){
	disableIconBtn("confirm"+salesOrderId);
	disableIconBtn("edit"+salesOrderId);
	disableIconBtn("pay"+salesOrderId);
	disableIconBtn("refund"+salesOrderId);
	disableIconBtn("pick"+salesOrderId);
	disableIconBtn("ship"+salesOrderId);
	disableIconBtn("return"+salesOrderId);
	disableIconBtn("complete"+salesOrderId);
	disableIconBtn("cancel"+salesOrderId);
	if(orderStatus == null){
		//case: 
	}else if(orderStatus == 0){
		//case:等待确认
		enableIconBtn("confirm"+salesOrderId);
		enableIconBtn("edit"+salesOrderId);
		enableIconBtn("cancel"+salesOrderId);
	}else if(orderStatus == 1 || orderStatus == 2){
		//case:已经确认 或 等待处理
		if(paymentStatus !=1){
			//非全额收款
			enableIconBtn("pay"+salesOrderId);
		}
		if(paymentStatus != 0 && paymentStatus!= -1 && isCanReturnMoney == 1) {
			//非未支付和全额退款
			enableIconBtn("refund"+salesOrderId);
		}			

		if (shipmentStatus != 1) {
			//非全部发货
			enableIconBtn("ship"+salesOrderId);
		}
		if (shipmentStatus != 0 && shipmentStatus!= -1) {
			//非未发货和全部退货
			enableIconBtn("return"+salesOrderId);
		}
		enableIconBtn("pick"+salesOrderId);
		enableIconBtn("complete"+salesOrderId);
		enableIconBtn("cancel"+salesOrderId);
		
		if(orderStatus == 1){
			//case:已经确认
			enableIconBtn("edit"+salesOrderId);
		}
	}
}	

//重新加载订单信息区
function refreshOrderItem(salesOrderId){
	//必须先使得全信息区隐藏并去掉hasLoad标志
	$j('#tr'+salesOrderId).next('tr').hide().removeClass("hasLoad");
	//重新加载
	$j('#tr'+salesOrderId).loading3().load(__ctxPath+"/order/salesOrder/blank.html?doAction=showOrderTr&salesOrderId="+salesOrderId);
	
}

//确认订单
function confirmOrder(salesOrderId){
	if(confirm(__FMT.salesOrder_process_confirmOrder_choose)){
		var postData = {"salesOrderId":salesOrderId};
		var url=__ctxPath+"/order/salesOrder/blank.html?doAction=confirmOrder";
	    $j.post(url,postData,confirmOrderCallback,"json");
	}
		
}

//确认订单callback
function confirmOrderCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	
	refreshOrderItem(data.salesOrderId);
}
//清空旧面板的内容，此方法用于避免不同面板有相同id造成的验证匹配
function clearPanel(){
	$j('#shipPanel').remove();
	$j('#returnPanel').remove();
	$j('#payPanel').remove();
	$j('#refundPanel').remove();
}

//显示收款面板
function showPayPanel(salesOrderId){
	clearPanel();
	dlgpayPanel_show({'salesOrderId':salesOrderId});	
}

//收款
function payOrder(){
	if(!validateForm($('payPanel')))	{
		alert(__vaMsg.notPass);
	}else{
		dlgpayPanel_close();
		displayButtons($j('#payPanel #salesOrderId').val(),null);
		$j('#tr'+$j('#payPanel #salesOrderId').val()).loading3();
		var postData = $j('#payPanel :input').serializeArray();
		var url=__ctxPath+"/order/salesOrder/blank.html?doAction=payOrder";
	    $j.post(url,postData,payOrderCallback,"json");
	}
}

//收款callback
function payOrderCallback(data){
	
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	refreshOrderItem(data.salesOrderId);
}


//显示退款面板
function showRefundPanel(salesOrderId){
	clearPanel();
	dlgrefundPanel_show({'salesOrderId':salesOrderId});	
}

//退款
function refundOrder(){
	if(!validateForm($('refundPanel')))	{
		alert(__vaMsg.notPass);
	}else{
		dlgrefundPanel_close();
		displayButtons($j('#refundPanel #salesOrderId').val(),null);		
		$j('#tr'+$j('#refundPanel #salesOrderId').val()).loading3();
		var postData = $j('#refundPanel :input').serializeArray();
		var url=__ctxPath+"/order/salesOrder/blank.html?doAction=refundOrder";
	    $j.post(url,postData,refundOrderCallback,"json");
	}
}

//退款callback
function refundOrderCallback(data){
	
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	refreshOrderItem(data.salesOrderId);
}


//显示发货面板
function showShipPanel(salesOrderId){
	clearPanel();
	dlgshipPanel_show({'salesOrderId':salesOrderId});	
}

//发货
function shipOrder(){
	var isVirtualAddress = ($j('#shipPanel #isVirtualAddress').length != 0)?true:false;
	if(!isVirtualAddress){
		//验证运输方式等
		var deliveryKind = $j('#shipPanel input[name="deliveryKind"]:checked').val();
		removeValidate($j('#shipPanel #shippingRateId').get(0));
		removeValidate($j('#shipPanel #selfCollectionCentreId').get(0));
		if(deliveryKind==1){
			applyValidate($j('#shipPanel #shippingRateId').get(0),"required");
		}else{
			applyValidate($j('#shipPanel #selfCollectionCentreId').get(0),"required");
		}
	}
	
	if(!validateForm($('shipPanel')))	{
		alert(__vaMsg.notPass);
		return;	
	}
	if (!isVirtualAddress) {
		if($j('#regionShowDiv input[name="regionId"]').length == 0){
			//判断地区是否在编辑中
			alert(__FMT.salesOrder_panel_region_needConfirm);
			return;
		}
	}
	
	
	var shipTotal = 0;
	$j('#shipPanel input[name="shipQuantity"]').each(function(){
		shipTotal += parseInt(this.value);
	});
	if(shipTotal == 0){
		//判断发货数量
		alert(__FMT.salesOrder_shipPanel_shipQuantityMustNotZero);
		return;
	}	
		
	displayButtons($j('#shipPanel #salesOrderId').val(),null);		
	dlgshipPanel_close();
	$j('#tr'+$j('#shipPanel #salesOrderId').val()).loading3();
	var postData = $j('#shipPanel :input').serializeArray();
	var url=__ctxPath+"/order/salesOrder/blank.html?doAction=shipOrder";
    $j.post(url,postData,shipOrderCallback,"json");
}

//发货callback
function shipOrderCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	refreshOrderItem(data.salesOrderId);
}

//渲染地区修改区域
function renderPanelRegionModifyDiv(buttonDom){
	var jPanel = $j(buttonDom).parents('div[name="shipmentPanel"]');
	var regionId = jPanel.find('input[name="regionId"]').val();
	jPanel.find('#regionModifyDiv').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=renderPanelRegionModify&regionId='+regionId);
	jPanel.find('#regionShowDiv').empty();
}
//渲染地区显示区域
function renderPanelRegionShowDiv(buttonDom){
	var jPanel = $j(buttonDom).parents('div[name="shipmentPanel"]');
	var salesOrderId = jPanel.find('#salesOrderId').val();
	if(validateForm(jPanel.find('#regionModifyDiv').get(0))){
		var regionId = jPanel.find('input[name="regionId"]').val();
		jPanel.find('#regionShowDiv').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=renderPanelRegionShow&regionId='+regionId);
		jPanel.find('#regionModifyDiv').empty();
		
		//加载配送方式
		jPanel.find('#shipPaneldeliveryTypeDiv').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=renderDeliveryType&regionId='+regionId+'&salesOrderId='+salesOrderId);
	}else{
		alert(__vaMsg.notPass);
	}
}


//显示退货面板
function showReturnPanel(salesOrderId){
	clearPanel();
	dlgreturnPanel_show({'salesOrderId':salesOrderId});	
}

//退货
function returnOrder(){
	if($j('#returnPanel input[name="shipQuantity"]').length == 0){
		//判断是否有退货物品
		alert(__FMT.salesOrder_returnPanel_noReturnObject);
		return;
	}
	
	var isVirtualAddress = ($j('#returnPanel #isVirtualAddress').length != 0)?true:false;
	if (!isVirtualAddress) {
		//验证运输方式等
		var deliveryKind = $j('#returnPanel input[name="deliveryKind"]:checked').val();
		removeValidate($j('#returnPanel #shippingRateId').get(0));
		removeValidate($j('#returnPanel #selfCollectionCentreId').get(0));
		if (deliveryKind == 1) {
			applyValidate($j('#returnPanel #shippingRateId').get(0), "required");
		}
		else {
			applyValidate($j('#returnPanel #selfCollectionCentreId').get(0), "required");
		}
	}	
	
	if(!validateForm($('returnPanel')))	{
		alert(__vaMsg.notPass);
		return;	
	}
	
	if (!isVirtualAddress) {
		if($j('#regionShowDiv input[name="regionId"]').length == 0){
			//判断地区是否在编辑中
			alert(__FMT.salesOrder_panel_region_needConfirm);
			return;
		}
	}
	
	
	var returnTotal = 0;
	$j('#returnPanel input[name="shipQuantity"]').each(function(){
		returnTotal += parseInt(this.value);
	});
	if(returnTotal == 0){
		//判断退货数量
		alert(__FMT.salesOrder_returnPanel_returnQuantityMustNotZero);
		return;
	}	
	//判断入库数量是否不大于退货数量
	var flag = true;
	$j('#returnPanel input[name="shipQuantity"]').each(function(){
		if(flag){
			var shipQuantity = parseInt(this.value);
			var jIncomingQuantity = $j(this).parents('tr:first').find('input[name="incomingQuantity"]');
			var incomingQuantity = parseInt(jIncomingQuantity.val());
			if(incomingQuantity > shipQuantity){
				alert(__FMT.salesOrder_returnPanel_returnQuantityMustGtIncomingQuantity);
				jIncomingQuantity.focus();
				flag = false;
				return;
			}
		}
	});
	if(!flag){
		return;
	}
		
	displayButtons($j('#returnPanel #salesOrderId').val(),null);		
	dlgreturnPanel_close();
	$j('#tr'+$j('#returnPanel #salesOrderId').val()).loading3();
	var postData = $j('#returnPanel :input').serializeArray();
	var url=__ctxPath+"/order/salesOrder/blank.html?doAction=returnOrder";
    $j.post(url,postData,returnOrderCallback,"json");
}

//退货callback
function returnOrderCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	refreshOrderItem(data.salesOrderId);
}


//显示完成订单面板
function showCompletePanel(salesOrderId){
	dlgcompletePanel_show({'salesOrderId':salesOrderId});	
}

//完成订单
function completeOrder(salesOrderId){
	if(!validateForm($('completePanel')))	{
		alert(__vaMsg.notPass);
		return;	
	}
	if(confirm(__FMT.salesOrder_process_completeOrder_choose)){
	    displayButtons($j('#completePanel #salesOrderId').val(),null);		
		dlgcompletePanel_close();
		$j('#tr'+$j('#completePanel #salesOrderId').val()).loading3();
		var postData = $j('#completePanel :input').serializeArray();
		var url=__ctxPath+"/order/salesOrder/blank.html?doAction=completeOrder";
	    $j.post(url,postData,completemOrderCallback,"json");
	}
		
}

//完成订单callback
function completemOrderCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	
	refreshOrderItem(data.salesOrderId);
}

//显示作废订单面板
function showCancelPanel(salesOrderId){
	dlgcancelPanel_show({'salesOrderId':salesOrderId});	
}

//作废订单
function cancelOrder(){
	if(!validateForm($('cancelPanel')))	{
		alert(__vaMsg.notPass);
		return;	
	}
	if (confirm(__FMT.salesOrder_process_cancelOrderByAdmin_choose)) {
		displayButtons($j('#cancelPanel #salesOrderId').val(),null);		
		dlgcancelPanel_close();
		$j('#tr'+$j('#cancelPanel #salesOrderId').val()).loading3();
		var postData = $j('#cancelPanel :input').serializeArray();
		var url=__ctxPath+"/order/salesOrder/blank.html?doAction=cancelOrderByAdmin";
	    $j.post(url,postData,cancelOrderCallback,"json");
	}
		
}

//作废订单callback
function cancelOrderCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}
	
	refreshOrderItem(data.salesOrderId);
}

//保存备注
function saveMemo(salesOrderId){
	if(!validateForm($('memoDiv'+salesOrderId)))	{
		alert(__vaMsg.notPass);
		return;	
	}
	var postData = $j('#memoDiv'+salesOrderId+' :input').serializeArray();
	var url=__ctxPath+"/order/salesOrder/blank.html?doAction=saveMemo";
    $j.post(url,postData,saveMemoCallback,"json");
}

//保存备注callback
function saveMemoCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);		
	}else{
		alert(__FMT.salesOrder_process_saveMemo_success);
	}
	
}


//打印订单
function printOrderList(){
	var paraData=$j(":input[name='multiIds']").serializeArray();
	if(paraData.length>0) {		
		var param = $j.param(paraData);
		var page = __ctxPath+'/order/salesOrder.html?doAction=printOrderList';
		window.open(page + "&" + param);
	}else{
		alert(__FMT.salesOrderList_selectSalesOrder);	 
	}	
}


//显示备货面板
function showPickPanel(){
	dlgpickPanel_show();	
}

//备货面板-添加订单 -多个
function addOrderNo4PickPanel(){
	var paraData=$j(":input[name='multiIds']").serializeArray();
	if(paraData.length>0) {		
		$j.post(__ctxPath+'/order/salesOrder.html?doAction=addOrderNo4PickPanel',paraData,addOrderNo4PickPanelCallback,"json");
	}else{
		alert(__FMT.salesOrderList_selectSalesOrder);	 
	}	
}

//备货面板-添加订单 -单个
function addSingleOrderNo4PickPanel(salesOrderId){
	var paraData = new Array();
	paraData.push({"name":"multiIds","value":salesOrderId});
	$j.post(__ctxPath+'/order/salesOrder.html?doAction=addOrderNo4PickPanel',paraData,addOrderNo4PickPanelCallback,"json");
}

//备货面板-添加订单callback
function addOrderNo4PickPanelCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);
		return;		
	}
	if(data.message != null){
		sysMsg(data.message,false);
		return;		
	}
}

//备货面板-移除多张订单
function removeOrderNo4PickPanel(){
	var paraData=$j("#orderNo4Pick").serializeArray();
	if(paraData.length>0) {		
		$j("#orderNo4Pick option:selected").remove();
		$j.post(__ctxPath+'/order/salesOrder.html?doAction=removeOrderNo4PickPanel',paraData,null,"json");
	}else{
		alert(__FMT.salesOrder_pickPanel_selectOrderNo_first);	 
	}	
}

//备货面板-清空订单
function removeAllOrderNo4PickPanel(){
	var paraData=$j("#orderNo4Pick").serializeArray();
	$j("#orderNo4Pick option").remove();
	$j.post(__ctxPath+'/order/salesOrder.html?doAction=removeAllOrderNo4PickPanel',null,null,"json");
}

//备货面板-备货动作
function pickOrder(){
	
	var paraData = $j("#orderNo4Pick option")
	if(paraData.length>0) {	
		if (confirm(__FMT.salesOrder_pickPanel_pickOrder_confirm)) {
			dlgpickPanel_close();	
			$j.post(__ctxPath+'/order/salesOrder.html?doAction=pickOrder',null,pickOrderCallback,"json");
		}
	}else{
		alert(__FMT.salesOrder_pickPanel_selectOrderNo_empty);
	}
}
//备货面板-备货动作callback
function pickOrderCallback(data){
	if(data.errorMessage != null){
		alert(data.errorMessage);
		return;		
	}
	if(data.message != null){
		sysMsg(data.message,false);
		return;		
	}
	if(data.failMessage != null){
		sysMsg(data.failMessage,true);
		return;		
	}
}


